package cn.pconline.autoclub.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserVoted;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.entity.VoteDetail;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.service.VoteService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.AbstractDyna;

/**
 * @author zhouruxuan
 * @date 2015年2月12日 下午6:34:34
 */
@Controller
@RequestMapping(value = "/vote")
public class VoteController {
	
	@Autowired
	private UserAuth userAuth;
	@Autowired
    private MemberService memberService;
	@Autowired
    private VoteService voteService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private DynaIndexService dynaIndexService;
    
	private static final Logger log = LoggerFactory.getLogger(VoteController.class);
	private static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
	
	/**
     * ajax操作的错误信息提示
     *
     * @param resp
     * @param msg
     * @param field
     * @
     */
    private void errorMsg(HttpServletResponse resp, String msg, String field) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("code", -1)
                    .put("field", field)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("errorMsg response out error");
        }
    }

    /**
     * ajax操作的成功信息提示
     *
     * @param resp
     * @param msg
     * @
     */
    private void successMsg(HttpServletResponse resp, String msg) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("code", 0)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("successMsg response out error");
        }
    }
    
    private void printSuccessMsg(HttpServletResponse resp, String msg, JSONObject data, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", AppUtils.STATUS_OK);
        if (StringUtils.isNotEmpty(msg)) {
            json.put("message", msg);
        }
        if (data != null) {
            json.put("data", data);
        }
        printMsg(resp, json.toJSONString(), callback);
    }
    
    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }
    
    /**
     * 发布投票
     * @param request
     * @param response
     */
    @RequestMapping(value = "/createVote.do", method = RequestMethod.POST)
    public void createVote(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding(request, response);
    	String callback = WebUtils.param(request, "callback", "");
    	String title = WebUtils.paramTrim( request, "voteTitle", "");
    	String[] voteItems = request.getParameterValues("voteItem");
    	JSONObject successObject = new JSONObject(); //成功发表的动态
        //获取用户信息
        User user = userAuth.getUser(request, response);
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
       	 this.errorMsg(response, "用户未登录", "");
            return;
        }
        long userId = user.getUid();
        //是否加入车友会
        ClubMember clubMember = memberService.findClubMemberByUserId(userId);
        if(clubMember == null) {
       	 this.errorMsg(response, "你还没加车友会", "");
            return;
        }
        if(title.isEmpty()){
        	this.errorMsg(response, "投票标题不能为空", "");
        	return;
        }
        if(title.length()> Vote.VOTETITLE_MAX_LENGTH){
        	this.errorMsg(response, "投票标题长度不能超过50", "");
        	return;
        }
        String[] validItem = new String[8];
        int validNum = 0;
        if(voteItems==null){
        	this.errorMsg(response, "请输入投票选项", "");
        	return;
        }
        for(String item:voteItems){
        	if(item!=null &&!item.isEmpty()){
        		validItem[validNum] = item;
        		validNum++;
        	}
        }
        if(validNum<2 || validNum>8){
        	this.errorMsg(response, "投票项个数[2-8]", "");
        	return;
        }
        HashSet<String> hashSet = new HashSet<String>();
        List<VoteDetail> voteDetails  = new ArrayList<VoteDetail>(); 
        for(String item:validItem){
        	if(item==null) continue;
        	if(item.length()> VoteDetail.VOTEITEM_MAX_LENGTH){
        		this.errorMsg(response, "投票项长度不能超过255", "");
        		return;
        	}
        	hashSet.add(item);
        	VoteDetail voteDetail = new VoteDetail();
   		 	voteDetail.setContent(item);
   		 	voteDetails.add(voteDetail);
        }
        if(hashSet.size()!=validNum){
        	this.errorMsg(response, "投票项不可以重复", "");
        	return;
        }
        
        long clubId = clubMember.getClubId();
        Club club = clubService.getValidClub(clubId);
        if(club == null) {
        	this.errorMsg(response, "车友会不存在", "");
        	return;
        }
        Vote vote = new Vote();
        vote.setClubId(clubId);
        vote.setCreateBy(user.getUid());
        vote.setCreateAt(new Date());
        vote.setUpdateBy(user.getUid());
        vote.setUpdateAt(new Date());
        vote.setVoteTitle(title);
        vote.setStatus(Vote.STATUS_NORMAL);
        boolean result = voteService.createVote(vote,voteDetails);
        if(!result){
        	this.errorMsg(response, "创建投票标题失败", "");
        	return;
        }
        AbstractDyna abstractDyna = new AbstractDyna();
        abstractDyna.setClubId(clubId);
        abstractDyna.setContent(title);
        abstractDyna.setTargetId(vote.getVoteId());
        abstractDyna.setCreateBy(user.getUid());
        abstractDyna.setCreateDate(new Date());
        abstractDyna.setCreateName(user.getUsername());
        long dynaId =dynaService.createVoteDyna(abstractDyna, null);
        
        //组装成功发表后对象（用于首页js刷新）
        successObject.put("content",  WebUtils.transformToBBSFace(title));
        successObject.put("templateId", "template-voteDyna");
        successObject.put("type", DynaInfo.TYPE_VOTE );
        successObject.put("voteId", vote.getVoteId() );
        successObject.put("voteTitle", EncodeUtils.encodeForHTMLFilterNull(title));
        successObject.put("voteCount",vote.getVoteCount());
        successObject.put("dynaDetailUrl", systemConfig.getRoot() + "/" + club.getClubUrl() + "/dt/" +dynaId + "/" );
        successObject.put("avatar", WebUtils.face(vote.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
        successObject.put("nickName", userService.findUser(vote.getCreateBy()).getNickname());
        successObject.put("userId", vote.getCreateBy());
        successObject.put("dynaInfoId", dynaId);
        successObject.put("year", DateUtils.format(vote.getCreateAt(), "yyyy"));
        successObject.put("createDate", DateUtils.format(vote.getCreateAt(), "yyyy-MM-dd HH:mm:ss"));
        successObject.put("fmtCreateDate", DateUtils.format(vote.getCreateAt(), "MM-dd HH:mm:ss"));
        successObject.put("praiseCount", 0);	//	刚发表点赞数默认为0
        successObject.put("postCount", 0);		//  刚发表回复数默认为0
        
        this.printSuccessMsg(response, "发表成功",successObject,callback);
    }
    

	
	/**
     * 用户进行投票
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/takeVote.do", method = RequestMethod.POST)
    public void takeVote(HttpServletRequest request, HttpServletResponse response) {
    	 WebUtils.setEncoding(request, response);
         //获取相关参数
         long voteId = WebUtils.paramLong(request, "voteId", 0);
         long voteItemId = WebUtils.paramLong(request, "voteItemId", 0);
         //获取用户信息
         User user = userAuth.getUser(request, response);
         //判断用户是否登录
         if (user == null || user.getUid() <= 0) {
        	 this.errorMsg(response, "用户未登录", "");
             return;
         }
         long userId = user.getUid();

         //是否加入车友会
         ClubMember clubMember = memberService.findClubMemberByUserId(userId);
         if(clubMember == null) {
        	 this.errorMsg(response, "你还没加车友会", "");
             return;
         }
               
         //投票信息校验
         Vote vote = voteService.getValidVote(voteId);
         VoteDetail voteDetail = voteService.findVoteDetailByVoteItemId(voteItemId);
         if(vote == null){
        	 this.errorMsg(response, "该投票活动不存在", "");
             return;
         }
         if(voteDetail == null){
        	 this.errorMsg(response, "该投票项不存在", "");
             return;
         }
         if(vote.getVoteId() != voteDetail.getVoteId()) {
        	 this.errorMsg(response, "该投票活动不存在此选项", "");
             return;
         }
         
         //是否本车友会的投票活动
         if(clubMember.getClubId() != vote.getClubId()) {
        	 this.errorMsg(response, "只能参加本车友会的投票活动", "");
             return;
         }
         
         //用户是否已经成功投票过
         UserVoted userVote = voteService.findVoteByUserId(voteId, userId);
         if(userVote != null) {
        	 this.errorMsg(response, "你已经成功投票过，不能重复投票", "");
             return;
         }
         
         long result = voteService.createUserVoted(vote, voteDetail, userId);
         
         if(result != 0){
        	 this.errorMsg(response, "用户投票失败", "");
             return;
         }
              
         this.successMsg(response, "投票成功");
    }
    
    /**
     * 删除投票
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/delVote.do", method = RequestMethod.POST)
    public void deleteVote(HttpServletRequest request, HttpServletResponse response){
    	WebUtils.setEncoding(request, response);
        //获取相关参数
    	long voteId = WebUtils.paramLong(request, "voteId", 0);
    	//获取用户信息
        User user = userAuth.getUser(request, response);
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
       	 this.errorMsg(response, "用户未登录", "");
            return;
        }
        //判断投票是否存在
        Vote vote = voteService.getValidVote(voteId);
        if(vote == null){
          	 this.errorMsg(response, "该投票活动不存在", "");
             return;
        }
        //判断登录用户是否有删除操作权限--管理员(副会长、会长)，或者投票发布者
        boolean hasDeleteRole = false;
        long userId = user.getUid();
        if(userId == vote.getCreateBy()){ // 投票创建者
        	hasDeleteRole = true;
        }else{
        	long clubId = vote.getClubId();
        	hasDeleteRole = memberService.isClubNormalAdmin(userId, clubId);
        }
        if(!hasDeleteRole){
         	 this.errorMsg(response, "没有删除权限", "");
             return;
        }
        //删除投票
        int deleteResult = voteService.deleteVote(voteId);
        //删除车友会投票动态
        if(deleteResult > 0) {
        	DynaInfo dynaInfo = dynaService.getDynaByTargetId( vote.getCreateAt(), voteId, DynaInfo.TYPE_VOTE );
        	if(dynaInfo != null) {
        		dynaService.deleteClubDyna(vote.getClubId(), dynaInfo.getDynaInfoId());	//删除车友会动态索引
        		dynaService.deleteUserDyna(vote.getCreateBy(), dynaInfo.getDynaInfoId());//删除车友会用户索引
        		dynaIndexService.deleteDynaIndex( dynaInfo.getDynaInfoId() );
        	}
        }
        this.successMsg(response, "删除成功");
        
    }
}
